package dmsxl.shuzu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Author: Zhang Dongwei
 * Date: 2023/4/7 9:48
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
 */
public class array6_r2_offer29 {

    public static void main(String[] args) {
//        int[][] matrix = {{1, 2, 3,4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        int[][] matrix = {};
        int[] res = spiralOrder(matrix);
        System.out.println(Arrays.toString(res));
    }

//    在54号题目的基础上修改的，自己写的，还行
    public static int[] spiralOrder1(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return new int[0];
        int row = matrix.length, col = matrix[0].length;
        int l=0, t=0, r=col-1, b=row-1, count=0;
        int[] res = new int[col*row];
        while (count<(col*row)){
            for (int i=l; i<=r; i++){
                if (count<(col*row)){
                    res[count] = matrix[t][i];
                    count ++;
                }
            }
            t++;
            for (int i=t; i<=b; i++){
                if (count<(col*row)){
                    res[count] = matrix[i][r];
                    count ++;
                }
            }
            r--;
            for (int i=r; i>=l; i--){
                if (count<(col*row)){
                    res[count] = matrix[b][i];
                    count ++;
                }
            }
            b--;
            for (int i=b; i>=t; i--){
                if (count<(col*row)){
                    res[count] = matrix[i][l];
                    count ++;
                }
            }
            l++;
        }
        return res;
    }

//    答案，比较简洁
    public static int[] spiralOrder(int[][] matrix) {
        if(matrix.length == 0) return new int[0];
        int l = 0, r = matrix[0].length - 1, t = 0, b = matrix.length - 1, x = 0;
        int[] res = new int[(r + 1) * (b + 1)];
        while(true) {
            for(int i = l; i <= r; i++) res[x++] = matrix[t][i]; // left to right.
            if(++t > b) break;
            for(int i = t; i <= b; i++) res[x++] = matrix[i][r]; // top to bottom.
            if(l > --r) break;
            for(int i = r; i >= l; i--) res[x++] = matrix[b][i]; // right to left.
            if(t > --b) break;
            for(int i = b; i >= t; i--) res[x++] = matrix[i][l]; // bottom to top.
            if(++l > r) break;
        }
        return res;
    }
}
